<template>
  <div class="roles">
    <!-- 面包屑导航区 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['vcenter', 'dbbottom',index1 === 0 ? 'dbtop':'']"
              v-for="(item1,index1) in scope.row.children"
              :key="index1"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag class="tag">{{item1.authname}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环渲染所有的列 -->
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="index2"
                  :class="['vcenter',index2 === 0? '':'dbtop']"
                >
                  <el-col :span="6">
                    <el-tag class="tag" type="success">{{item2.authname}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <!-- 三级渲染 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      class="tag"
                      v-for="(item3,index3) in item2.children"
                      :key="index3"
                      @close="removeRight(scope.row._id,scope.row,index1,index2,index3)"
                    >{{item3.authname}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="rolename"></el-table-column>
        <el-table-column label="角色描述" prop="roledesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            </el-tooltip>

            <!-- 删除 -->
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            </el-tooltip>

            <!-- 分配权限 -->
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRoles(scope.row)"
              >分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showSetRolesVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 内容 -->
      <el-tree
        ref="treeRef"
        :data="rights"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defkey"
      ></el-tree>

      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "roles",
  created() {
    this.getRolesList();
  },
  data() {
    return {
      rolesList: null,
      // 控制分配权限的对话框是否显示
      showSetRolesVisible: false,
      // 所有权限的数据
      rights: null,
      // 树形控件属性绑定事件
      treeProps: {
        label: "powername",
        children: "children"
      },
      // 默认勾选的节点ID
      defkey: []
    };
  },
  methods: {
    async getRolesList() {
      let anonymousLogin = await this.$login();
      // 若匿名登录失败就直接停止了
      if (!anonymousLogin) return;
      let res = await this.$cloudbase.callFunction({
        name: "roles",
        data: {
          methods: "getRolesList"
        }
      });
      this.rolesList = res.result.data;
    },
    // 根据Id删除用户的权限
    async removeRight(id, value, index1, index2, index3) {
      let rescon = await this.$confirm("是否要删除该权限", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);
      if (rescon === "cancel") {
        return this.$message.info(`取消了删除`);
      }
      value.children[index1].children[index2].children.splice(index3, 1);
      let anonymousLogin = await this.$login();
      // 若匿名登录失败就直接停止了
      if (!anonymousLogin) return;
      let res = await this.$cloudbase.callFunction({
        name: "roles",
        data: {
          methods: "removeRight",
          data: {
            id,
            value
          }
        }
      });
      if (!res.result.requestId) {
        this.$message.error(`删除权限失败`);
      }
      this.$message.success(`删除权限成功了`);
      // 不需要重新获取数据了，因为已经在原来的数据上修改了
    },
    // 展示分配权限的对话框
    async showSetRoles(role) {
      // 获取到所有的三级节点的Id
      this.getDefkeys(role, this.defkey);
      // 获取所有权限的数据
      let anonymousLogin = await this.$login();
      // 若匿名登录失败就直接停止了
      if (!anonymousLogin) return;
      let res = await this.$cloudbase.callFunction({
        name: "rights",
        data: {
          methods: "setRoles"
        }
      });
      this.rights = res.result.data;
      this.showSetRolesVisible = true;
    },
    // 通过递归的形式，获取角色下所有的三级权限Id,并保存到defkey的数组中
    async getDefkeys(node, arr) {
      // 先判断该节点是否为三级节点，若该节点没有children则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      // 开始使用递归
      node.children.forEach(item => {
        this.getDefkeys(item, arr);
      });
    },
    // 监听分配权限对话框的事件
    setRightDialogClosed() {
      this.defkey = [];
    },

    async allotRights() {
      let keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$ref.treeRef.getHalfCheckedKeys()
      ];
      console.log(keys);
      // 将数组变成以英文的状态来拼接
      keys = keys.join(",");
      // 将数组传递给后台保存
      console.log(keys);

      // 最后将对话框隐藏
      this.showSetRolesVisible = false;
    }
  }
};
</script>
<style lang="less" scoped>
.tag {
  margin: 7px;
  cursor: pointer;
}
.dbtop {
  border-top: 1px solid #eeeeee;
}
.dbbottom {
  border-bottom: 1px solid #eeeeee;
  -webkit-user-select: none;
  user-select: none;
}
// 垂直居中
.vcenter {
  display: flex;
  align-items: center;
}
.el-card {
  max-height: calc(100vh - 135px);
  overflow-y: auto;
}
</style>